<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 ---管理员 -->
    <el-card v-if="currentUserInfo.role === '管理员'">
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input
            placeholder="请输入要查询的登录名"
            v-model="queryInfo.query"
            clearable
            @change="getUserList"
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="登录名" prop="username"></el-table-column>
        <el-table-column label="昵称" prop="nickname"></el-table-column>
        <el-table-column label="手机" prop="phone"></el-table-column>
        <el-table-column label="角色" prop="role"></el-table-column>
        <!-- <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChanged(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column> -->
        <el-table-column label="操作" width="240px">
          <template slot-scope="scope">
            <!-- {{ scope.row.id }}  -->
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
            ></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-s-help"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
            <!-- 重置密码按钮 -->
            <el-tooltip
              effect="dark"
              content="重置密码"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="resetPwd(scope.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- ------------------------------------------------------------------------------- -->
    <el-card v-if="currentUserInfo.role !== '管理员'">
      <!-- 用户列表区域 -->
      <!-- 内容主题区域 -->
      <el-form
        :model="currentUserInfo"
        :rules="currentUserInfoRules"
        ref="currentUserInfoRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="currentUserInfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="currentUserInfo.nickname"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="currentUserInfo.phone"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-input v-model="currentUserInfo.role"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="editUserInfo(currentUserInfo.id)"
            >保存</el-button
          >
          <el-button type="primary" @click="resetPwd(currentUserInfo.id)"
            >修改密码</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
    <!-- ---------------------------------------------------------------- -->
    <!-- 添加用户的对话框 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addDialogClosed"
    >
      <!-- 内容主题区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="addForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-input v-model="addForm.role"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户的对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <!-- 内容主题区域 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="editForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <!-- <el-input v-model="editForm.role"></el-input> -->
          <el-select v-model="selectedRoled" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.role"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRoleDialogVisible"
      width="50%"
      @close="setRoleDialogClosed"
    >
      <div>
        <p>当前的用户： {{ userInfo.username }}</p>
        <p>当前的角色： {{ userInfo.role }}</p>
        <p>
          分配新角色：
          <el-select v-model="selectedRoled" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.role"
              :label="item.role"
              :value="item.role"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户密码的对话框 -->
    <el-dialog
      title="修改用户密码"
      :visible.sync="resetPwdDialogVisible"
      width="50%"
      @close="resetPwdDialogClosed"
    >
      <!-- 内容主题区域 -->
      <el-form
        :model="resetPwdForm"
        :rules="resetPwdFormRules"
        ref="resetPwdFormRef"
        label-width="80px"
      >
        <el-form-item label="用户名">
          <el-input v-model="resetPwdForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="resetPwdForm.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="repassword">
          <el-input v-model="resetPwdForm.repassword"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetPwdDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="resetPwdInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'userManagement',
  data() {
    // 自定义验证邮箱的规则
    var checkEmail = (rules, value, cb) => {
      // 验证邮箱的正则表达式
      const regEmail =
        /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/

      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb()
      }
      // 非法的邮箱
      cb(new Error('请输入合法的邮箱'))
    }
    // 自定义验证手机号的规则
    var checkphone = (rules, value, cb) => {
      // 验证手机号的正则表达式
      const regphone = /^1[3|4|5|7|8][0-9]{9}$/

      if (regphone.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法的手机号'))
    }
    // 验证新旧密码
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.resetPwdForm.repassword !== '') {
          this.$refs.resetPwdFormRef.validateField('repassword')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.resetPwdForm.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      // searchTxt: '',
      // searchValue: '',
      tableData: [],
      token: '',
      // -----------------
      // 获取用户列表的参数对象
      queryInfo: {
        query: '',
        // 当前的页数
        pagenum: 1,
        // 当前每页显示多少条数据
        pagesize: 5,
      },
      userlist: [],
      total: 0,
      // 控制添加用户对话框的显示与隐藏
      addDialogVisible: false,
      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        nickname: '',
        phone: '',
        role: '',
      },
      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3到10 个字符之间',
            trigger: 'change',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '长度在 6到15 个字符之间',
            trigger: 'change',
          },
        ],
        nickname: [
          { message: '请输入昵称', trigger: 'blur' },
          // { validator: checkEmail, trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '请输入手机', trigger: 'change' },
          { validator: checkphone, trigger: 'change' },
        ],
        role: [{ message: '请输入用户角色', trigger: 'blur' }],
      },
      // 控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的用户信息对象
      editForm: {},
      // 修改表单的 验证规则对象
      editFormRules: {
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '请输入用户手机号', trigger: 'blur' },
          { validator: checkphone, trigger: 'blur' },
        ],
      },
      // 控制分配角色对话框的显示与隐藏
      setRoleDialogVisible: false,
      // 需要被分配角色（那一行）的用户信息
      userInfo: {},
      // 所有角色的数据列表
      rolesList: [],
      // 已选中的角色id值
      selectedRoled: '',

      // 重置密码
      resetPwdDialogVisible: false,
      resetPwdForm: {
        id: '',
        username: '',
        password: '',
        repassword: '',
      },
      resetPwdFormRules: {
        password: [
          { required: true, message: '请输入密码', trigger: 'change' },
          { validator: validatePass, trigger: 'change' },
        ],
        repassword: [
          { required: true, message: '请再次输入密码', trigger: 'change' },
          { validator: validatePass2, trigger: 'change' },
        ],
      },
      currentUserInfo: {},
      currentUserInfoRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3到10 个字符之间',
            trigger: 'change',
          },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '长度在 6到15 个字符之间',
            trigger: 'change',
          },
        ],
        nickname: [
          { message: '请输入昵称', trigger: 'blur' },
          // { validator: checkEmail, trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '请输入手机', trigger: 'change' },
          { validator: checkphone, trigger: 'change' },
        ],
        role: [{ message: '请输入用户角色', trigger: 'blur' }],
      },
    }
  },
  created() {
    // 根据传进来的id 发起 axios请求，得到对用户的信息
    this.$http.get('/myApi/my/userinfo/').then((res) => {
      console.log(res.data, '???????')
      if (res.data.code !== 200) {
        return this.$message.error('查询当前用户信息失败')
      }
      this.$message.success('查询用户信息成功')
      // 请求成功后将用户的信息保存到 data中
      this.currentUserInfo = res.data.data
      this.$store.commit('setUserInfo', this.currentUserInfo)
    })
    this.getUserList()
    console.log(this.currentUserInfo, '[[[[[[[[[[[[[[[')
  },
  computed: {
    getuserInfo() {
      return this.$store.state.userInfo
    },
  },
  methods: {
    // 获取所有用户信息
    getUserList() {
      this.$http
        .get('/myApi/my/userinfoAll', {
          params: this.queryInfo,
        })
        .then((res) => {
          console.log(res.data, '00000000000')
          if (res.data.code == 200) {
            this.userlist = res.data.data
            this.total = res.data.total
          }
        })
    },
    // 修改对话框
    async showEditDialog(id) {
      // 根据传进来的id 发起 axios请求，得到对用户的信息
      const { data: res } = await this.$http.get('/myApi/my/userinfo/' + id)
      console.log(res, '???????')
      if (res.code !== 200) {
        return this.$message.error('查询用户信息失败')
      }
      this.$message.success('查询用户信息成功')
      // 请求成功后将用户的信息保存到 data中
      this.editForm = res.data
      this.selectedRoled = this.editForm.role
      // 在展示对话框之前， 获取所有的角色的列表
      const { data: res1 } = await this.$http.get('/myApi/my/roles')

      if (res1.code !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      console.log(res1.data, 'role  role')
      this.rolesList = res1.data

      this.editDialogVisible = true
      // console.log(id)
    },
    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 修改用户信息并提交
    editUserInfo() {
      // validate()是提交前 对整个表单进行校验的方法
      this.$refs.editFormRef.validate(async (valid) => {
        // console.log(valid)
        if (!valid) return
        // 可以发起修改用户的网络请求
        const { data: res } = await this.$http.post(
          '/myApi/my/userinfo/' + this.editForm.id,
          {
            id: this.editForm.id,
            nickname: this.editForm.nickname,
            phone: this.editForm.phone,
            role: this.editForm.role,
          }
        )
        console.log(res)
        if (res.code !== 200) {
          return this.$message.error('更新用户信息失败')
        }
        // 隐藏修改用户的对话框
        this.editDialogVisible = false
        // 重新渲染数据
        this.getUserList()
        // 提示修改成功
        this.$message.success('更新用户信息成功')
      })
    },
    // 根据id 删除对应的用户信息
    async removeUserById(id) {
      // 弹框询问用户是否删除数据
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err) // cancel
      // 如果用户点击确认 删除，则返回值为 字符串 confirm
      // 如果用户点击取消 删除，则返回值为 字符串 cancel
      // console.log(confirmResult) // Promise对象
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除!')
      }
      // console.log('确认了删除')
      const { data: res } = await this.$http.delete('/myApi/my/userinfo/' + id)

      if (res.code !== 200) {
        return this.$message.error('删除用户信息失败!')
      }
      this.$message.success('删除用户信息成功')
      // 重新渲染列表
      this.getUserList()
    },
    // 展示分配角色的对话框
    async setRole(userInfo) {
      this.userInfo = userInfo

      // 在展示对话框之前， 获取所有的角色的列表
      const { data: res } = await this.$http.get('/myApi/my/roles')

      if (res.code !== 200) {
        return this.$message.error('获取角色列表失败！')
      }
      console.log(res.data, 'role  role')
      this.rolesList = res.data

      this.setRoleDialogVisible = true
    },
    // 点击 分配角色对话框的‘确认’ 按钮
    async saveRoleInfo() {
      if (!this.selectedRoled) {
        return this.$message.error('请选择要分配的角色！')
      }

      const { data: res } = await this.$http.get(
        `/myApi/my/userinfoRole/${this.userInfo.id}`,
        {
          params: { role: this.selectedRoled },
        }
      )
      if (res.code !== 200) {
        return this.$message.error('更新角色失败！')
      }
      this.$message.success('更新角色成功')
      // 重新渲染列表数据
      this.getUserList()
      // 隐藏对话框
      this.setRoleDialogVisible = false
    },
    // 监听分配角色对话框的关闭事件
    setRoleDialogClosed() {
      this.selectedRoled = ''
      this.userInfo = {}
    },
    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      // 拿到对话框的引用，调用自身的resetFields方法，重置表单
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户信息
    addUser() {
      this.$refs['addFormRef'].validate((valid) => {
        // 校验失败
        if (!valid) return console.log('添加用户信息失败!!')
        // 添加用户信息
        this.$http.post('/myApi/my/addUserinfo', this.addForm).then((res) => {
          console.log(res.data)
          if (res.data.code !== 200) {
            this.$message.warning('添加失败，用户名或密码错误')
          } else {
            this.$message.success('添加用户成功')
            // 隐藏添加用户的对话框
            this.addDialogVisible = false
            this.getUserList()
          }
        })
      })
    },
    // 分页=========
    // 监听pagesize 改变的事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      console.log(this.queryInfo.pagesize, 'pagesize')
      this.getUserList()
    },
    // 监听页码值改变的事件
    handleCurrentChange(newPage) {
      // console.log(newPage)
      this.queryInfo.pagenum = newPage
      console.log(this.queryInfo.pagenum, 'pagenum')
      this.getUserList()
    },
    // 监听 switch 开关状态的变化
    async userStateChanged(userinfo) {
      // console.log(userinfo)
      // const { data: res } = await this.$http.put(
      //   `users/${userinfo.id}/state/${userinfo.mg_state}`
      // )
      // if (res.meta.status !== 200) {
      //   userinfo.mg_state = !userinfo.mg_state
      //   return this.$message.error('更新用户状态失败')
      // }
      this.$message.success('更新用户状态成功')
    },
    // 重置密码
    async resetPwd(id) {
      // 根据传进来的id 发起 axios请求，得到对用户的信息
      const { data: res } = await this.$http.get('/myApi/my/userinfo/' + id)
      console.log(res, '???????')
      if (res.code !== 200) {
        return this.$message.error('查询用户信息失败')
      }
      this.$message.success('查询用户信息成功')
      // 请求成功后将用户的信息保存到 data中
      this.resetPwdForm.username = res.data.username
      this.resetPwdForm.id = res.data.id

      this.resetPwdDialogVisible = true
    },
    // 监听重置密码对话框的关闭事件
    resetPwdDialogClosed() {
      this.resetPwdForm = {
        id: '',
        username: '',
        password: '',
        repassword: '',
      }
    },
    // 点击修改密码对话框 确认按钮
    async resetPwdInfo() {
      const { data: res } = await this.$http.post(
        '/myApi/my/updatepwd/' + this.resetPwdForm.id,
        this.resetPwdForm
      )
      console.log(res, '.............')
      if (res.code !== 200) {
        return this.$message.error('更改用户密码失败')
      }
      this.$message.success('更改用户密码成功')
      this.resetPwdDialogVisible = false
    },
    async editUserInfo(id) {
      const { data: res } = await this.$http.post(
        '/myApi/my/userinfo/' + id,
        this.currentUserInfo
      )
      console.log(res, '.............')

      if (res.code !== 200) {
        return this.$message.error('更改用户信息失败')
      }
      this.$message.success('更改用户信息成功')
    },
  },
}
</script>

<style lang="less" scoped>
.el-select .el-input {
  width: 130px;
}
.input-with-select .el-input-group__prepend {
  background-color: #fff;
}
</style>
